package com.jhmk.jhecis.interceptor;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.jhmk.jhecis.domain.common.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import jakarta.servlet.http.HttpServletRequest;
/*
   全局异常处理
 */
@RestControllerAdvice

public class GlobalResponseInterceptor   {
    private static final Logger log = LoggerFactory.getLogger(GlobalResponseInterceptor.class);


//    @ExceptionHandler({NotPermissionException.class})
//    public R<Boolean> handleNotPermissionException(NotPermissionException e, HttpServletRequest request) {
//        String requestURI = request.getRequestURI();
//        log.error("请求地址'{}',权限码校验失败'{}'", requestURI, e.getMessage());
//        return AjaxResult.error(403, "没有访问权限，请联系管理员授权");
//    }
//
//    @ExceptionHandler({NotRoleException.class})
//    public R<Boolean> handleNotRoleException(NotRoleException e, HttpServletRequest request) {
//        String requestURI = request.getRequestURI();
//        log.error("请求地址'{}',角色权限校验失败'{}'", requestURI, e.getMessage());
//        return AjaxResult.error(403, "没有访问权限，请联系管理员授权");
//    }

    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public R<Boolean> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
        return R.fail(e.getMessage());
    }

//    @ExceptionHandler({ServiceException.class})
//    public R<Boolean> handleServiceException(ServiceException e, HttpServletRequest request) {
//        log.error(e.getMessage(), e);
//        Integer code = e.getCode();
//        return StringUtils.isNotNull(code) ? AjaxResult.error(code, e.getMessage()) : AjaxResult.error(e.getMessage());
//    }

    @ExceptionHandler({MissingPathVariableException.class})
    public R<Boolean> handleMissingPathVariableException(MissingPathVariableException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求路径中缺少必需的路径变量'{}',发生系统异常.", requestURI, e);
        return R.fail(String.format("请求路径中缺少必需的路径变量[%s]", e.getVariableName()));
    }

    @ExceptionHandler({MethodArgumentTypeMismatchException.class})
    public R<Boolean> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        String value = Convert.toStr(e.getValue());
//        if (StrUtil.isNotEmpty(value)) {
//            value = EscapeUtil.clean(value);
//        }

        log.error("请求参数类型不匹配'{}',发生系统异常.", requestURI, e);
        return R.fail(String.format("请求参数类型不匹配，参数[%s]要求类型为：'%s'，但输入值为：'%s'", e.getName(), e.getRequiredType().getName(), value));
    }

    @ExceptionHandler({RuntimeException.class})
    public R<Boolean> handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生未知异常.", requestURI, e);
        return R.fail(e.getMessage());
    }

    @ExceptionHandler({Exception.class})
    public R<Boolean> handleException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生系统异常.", requestURI, e);
        return R.fail(e.getMessage());
    }

    @ExceptionHandler({BindException.class})
    public R<Boolean> handleBindException(BindException e) {
        log.error(e.getMessage(), e);
        String message = ((ObjectError)e.getAllErrors().get(0)).getDefaultMessage();
        return R.fail(message);
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return R.fail(message);
    }
//
//    @ExceptionHandler({InnerAuthException.class})
//    public AjaxResult handleInnerAuthException(InnerAuthException e) {
//        return AjaxResult.error(e.getMessage());
//    }

//
//    @Override
//    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
//        return true;
//    }
//
//    @Override
//    public Object beforeBodyWrite(Object body,
//                                  MethodParameter methodParameter,
//                                  MediaType mediaType,
//                                  Class<? extends HttpMessageConverter<?>> aClass,
//                                  ServerHttpRequest serverHttpRequest,
//                                  ServerHttpResponse serverHttpResponse) {
//        final String returnTypeName = methodParameter.getParameterType().getName();
//
//        if("void".equals(returnTypeName)) {
//            // 返回类型为void
//            return R.ok(null);
//        } else if(!mediaType.includes(MediaType.APPLICATION_JSON) || "com.yyl.system.response.ResultInfo".equals(returnTypeName)) {
//            return body;
//        }
//        return R.fail(body);
//    }
}
